package com.glsc.ngateway.common.base.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class EncodeUtils {
    /**
     * 只编码中文字符
      */
    public static String encodeChinese(String input) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        for (char c : input.toCharArray()) {
            if (isChineseCharacter(c)) {
                result.append(URLEncoder.encode(String.valueOf(c), StandardCharsets.UTF_8));
            } else if(c == ' '){
                result.append("%20");
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

    /**
     * 判断字符是否为中文字符
      */
    public static boolean isChineseCharacter(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
    }
}
